<template>
  <div class="box">
    <div class="top">
      <h1 class="title01">光照管理</h1>
      <div class="operation">
        <el-select
          v-model="searchValue"
          clearable
          placeholder="请选择信息状态"
          style="width: 170px; margin: 0 10px 0 10px"
        >
          <el-option
            v-for="item in optionsInformationState"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="handleSearch" :loading="loading"
          >查询</el-button
        >
        <el-button
          type="primary"
          @click="OpenDialog('', 'add')"
          :disabled="equipmentInexistence"
          >新增</el-button
        >
      </div>
    </div>
    <!-- 内容 -->
    <div class="main">
      <!-- 表格渲染内容 -->
      <div class="table">
        <el-table :data="tableData" style="width: 100%" empty-text="暂无数据">
          <el-table-column fixed label="序号" width="60">
            <template #default="{ $index }">
              {{ startIndex + $index }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="plantname" label="植物名" /> -->

          <!-- <el-table-column prop="lightstate" label="光照状态">
            <template #default="scope">
              <div v-if="scope.row.lightstate === 0" style="color: green">
                已启动
              </div>
              <div v-else-if="scope.row.lightstate === 1">未启动</div>
              <div v-else style="color: red">故障</div>
            </template>
          </el-table-column> -->
          <el-table-column prop="startdate" label="照明开始日期" width="160">
            <template #default="scope">
              {{ parseTime(scope.row.startdate, "{y}-{m}-{d}") }}
            </template>
          </el-table-column>
          <el-table-column prop="enddate" label="照明结束日期" width="160">
            <template #default="scope">
              {{ parseTime(scope.row.enddate, "{y}-{m}-{d}") }}
            </template>
          </el-table-column>
          <el-table-column label="每日照明时间段">
            <template #default="scope">
              {{ scope.row.starttime }} 至 {{ scope.row.endtime }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="endtime" label="照明结束时间" width="160" /> -->
          <el-table-column prop="remark" label="删除原因" align="center">
            <template #default="scope">
              <div v-if="scope.row.delstate === 1">
                <div v-if="!scope.row.remark">
                  {{ "历史数据，无法修改" }}
                </div>
                <div v-else>
                  {{ scope.row.remark }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default="scope">
              <!-- <el-button
                link
                type="primary"
                size="small"
                :disabled="scope.row.delstate === 1"
                @click="OpenDialog(scope.row, 'edit')"
                >修改</el-button
              > -->
              <el-button
                link
                type="primary"
                size="small"
                :disabled="scope.row.delstate === 1"
                @click="DeleteForm(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 模态窗/新增列表 -->
    <el-dialog v-model="dialogVisible" width="550" :before-close="handleClose">
      <h1 class="title01">
        {{ dialogTitle ? "修改光照信息" : "新增光照信息" }}
      </h1>
      <el-form
        ref="ruleFormRef"
        :model="NewForm"
        :rules="FormRules"
        class="form"
      >
        <!-- 日期选择 -->
        <div class="timeInput">
          <el-form-item
            label="开始日期"
            prop="startdate"
            label-width="120px"
            label-position="left"
          >
            <el-config-provider :locale="locale">
              <el-date-picker
                v-model="NewForm.startdate"
                type="date"
                placeholder="选择开始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                controls-position="right"
              />
            </el-config-provider>
          </el-form-item>
          <el-form-item
            label="结束日期"
            prop="enddate"
            label-width="120px"
            label-position="left"
            class="justify-label"
          >
            <el-config-provider :locale="locale">
              <el-date-picker
                v-model="NewForm.enddate"
                type="date"
                placeholder="选择结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                :disabled-date="disabledDate"
                controls-position="right"
              />
            </el-config-provider>
          </el-form-item>
        </div>
        <!-- 时间段 -->
        <div style="width: 500px">
          <el-form-item
            label="开始照明时间段"
            label-width="120px"
            prop="starttime"
            label-position="left"
          >
            <el-config-provider :locale="locale">
              <el-time-select
                v-model="NewForm.starttime"
                style="width: 180px"
                :max-time="NewForm.endtime"
                class="mr-4"
                placeholder="选择开始时间"
                start="00:00"
                step="00:30"
                end="23:30"
              />
            </el-config-provider>
          </el-form-item>
          <el-form-item
            label="结束照明时间段"
            label-width="120px"
            prop="endtime"
            label-position="left"
          >
            <el-config-provider :locale="locale">
              <!-- <div style="margin: 0 10px 0 10px">至</div> -->
              <el-time-select
                v-model="NewForm.endtime"
                style="width: 180px"
                :min-time="NewForm.starttime"
                placeholder="选择结束时间"
                start="00:00"
                step="00:30"
                end="23:30"
              />
            </el-config-provider>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="ConfirmAddition"
            >提交</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 删除的弹窗 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="你确认要删除吗？"
      width="500"
      :before-close="handleClose"
    >
      <div style="display: flex; margin: 5px 0 0 0">
        <div style="margin: 0px 15px 10px 0">请输入删除原因</div>
        <div v-if="remarkExceedsLimit" class="error-message">
          字数超出限制！
        </div>
        <div v-else>
          {{ `${NewForm.remark.length}/25` }}
        </div>
      </div>
      <div style="width: 350px">
        <el-input
          v-model="NewForm.remark"
          maxlength="25"
          :class="{ 'error-input': remarkExceedsLimit }"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="loading" @click="confirmDeletion"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <div class="example-pagination-block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.currentPage"
        :page-size="pageInfo.pageSize"
        :total="pageInfo.total"
        layout="prev, pager, next"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import zhCn from "element-plus/es/locale/lang/zh-cn";
const locale = zhCn;
import {
  getLightList,
  queryLightList,
  deleteLightList,
  addLightList,
  updateLightList,
  queryLightEquipment,
} from "@/api/light/index";

// 分页
const pageInfo = reactive({
  // 当前页码
  pageNum: 1,
  // 每页显示条数
  pageSize: 10,
});

// 根据当前页码和每页显示条数计算出每条数据的序号
const startIndex = computed(() => {
  return (pageInfo.pageNum - 1) * pageInfo.pageSize + 1;
});

// 限制文本域输入字数
const remarkExceedsLimit = computed(() => {
  return NewForm.remark.length >= 25;
});

// 表格数据
const tableData = ref([]);

//用于判断设备是否存在
const equipmentInexistence = ref(true);
//暂存设备ID
const did = ref("");

// 搜索框内容
const searchValue = ref("");
// 搜索类型
const searchClass = ref("delstate");
// 搜索项目
const optionsInformationState = [
  {
    value: "0",
    label: "正常的",
  },
  {
    value: "1 ",
    label: "已删除的",
  },
];

// 模态窗状态
const dialogVisible = ref(false);
// 用于确认模态窗标题状态和新增修改状态
const dialogTitle = ref(false);
// 删除弹窗状态
const deleteDialogVisible = ref(false);

// 加载状态
const loading = ref(false);
// 限制日期选择范围
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 86400000;
};

// 重置表单
const ruleFormRef = ref(null);

// 新增/修改表单
const NewForm = reactive({
  // 光照ID
  lid: "",
  plantname: "",
  // 光照名称
  strength: "",
  // 设备ID
  did: "",
  // 开始日期
  startdate: "",
  // 结束日期
  enddate: "",
  // 开始时间
  starttime: "",
  // 结束时间
  endtime: "",
  //删除状态//  0：未删除  1：已删除
  delstate: "0",
  // 删除原因
  remark: "",
});

// 表单验证规则，验证日期选择器是否合法
const validateStartday = (rule, value, callback) => {
  if (NewForm.startdate && NewForm.enddate) {
    const start = new Date(NewForm.startdate).getTime();
    const end = new Date(NewForm.enddate).getTime();
    if (start > end) {
      callback(new Error("开始时间不能比结束时间晚"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

const FormRules = {
  did: [{ required: true, message: "请输入设备ID", trigger: "blur" }],
  startdate: [
    { required: true, message: "请选择开始日期", trigger: "blur" },
    { validator: validateStartday, trigger: "blur" },
  ],
  enddate: [
    { required: true, message: "请选择结束日期", trigger: "blur" },
    { validator: validateStartday, trigger: "blur" },
  ],
  starttime: [{ required: true, message: "请选择照明时间段", trigger: "blur" }],
  endtime: [{ required: true, message: "请选择照明时间段", trigger: "blur" }],
};

// 获取表格数据，请求数据，渲染表格
const gettableData = async () => {
  loading.value = true;
  try {
    let res = await getLightList({
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
    });
    if (res.code === 200) {
      tableData.value = res.data.records;
      pageInfo.total = res.data.total;
    }
  } catch (error) {
    ElMessage.error("获取数据失败，请重试");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 获取设备状态，确认用户是否拥有设备，
const getLightEquipment = async () => {
  let res = await queryLightEquipment();
  if (res.code === 200) {
    if (res.data !== null) {
      // 设备存在
      equipmentInexistence.value = false;
      did.value = res.data[0].did;
    } else {
      // 设备不存在
      equipmentInexistence.value = true;
      ElMessage.error("您当前没有设备");
    }
  } else {
    ElMessage.error("获取设备信息失败，请重试");
  }
};

// 页码变化时触发
const handleCurrentChange = (val) => {
  pageInfo.pageNum = val;
  gettableData();
};

// 页面展示数据变化时触发
const handleSizeChange = (val) => {
  pageInfo.pageSize = val;
  gettableData();
};

// 打开模态窗，通过判断type判断是新增还是修改，渲染表单
const OpenDialog = (row, type) => {
  dialogVisible.value = true;
  if (type === "edit" && row) {
    dialogTitle.value = true;
    Object.assign(NewForm, row);
  } else if (type === "add") {
    dialogTitle.value = false;
    resetNewForm();
    NewForm.did = did.value;
  } else {
    ElMessage.error("无效的操作类型");
    dialogVisible.value = false;
  }
};

// 确认按钮触发，验证表单，提交数据，关闭模态窗，刷新表格
const ConfirmAddition = async () => {
  loading.value = true;
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = dialogTitle.value
          ? await updateLightList(NewForm)
          : await addLightList(NewForm);

        if (res.code === 200) {
          ElMessage.success(res.msg);
          gettableData();
          handleClose();
        }
      } catch (error) {
        ElMessage.error("操作失败，请重试");
        console.error(error);
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage.error("请输入完整的有效信息");
      loading.value = false;
      return;
    }
  });
};

const handleClose = () => {
  dialogVisible.value = false;
  deleteDialogVisible.value = false;
  resetNewForm();
};

// 搜索按钮触发，请求数据，渲染表格
const handleSearch = async () => {
  loading.value = true;
  try {
    if (!searchValue.value) {
      gettableData();
      return;
    }
    let res = await queryLightList({
      searchClass: searchClass.value,
      searchValue: searchValue.value,
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
    });
    if (res.code === 200) {
      tableData.value = res.data.records;
      pageInfo.total = res.data.total;
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error("搜索操作失败，请重试");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 删除弹窗触发，确认删除时发送该列数据的删除状态，和删除原因
const confirmDeletion = async () => {
  loading.value = true;
  try {
    NewForm.delstate = 1;
    const res = await updateLightList(NewForm);
    if (res.code === 200) {
      ElMessage.success("标记删除成功");
      gettableData();
      handleClose();
    }
  } catch (error) {
    ElMessage.error("操作失败，请重试");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 删除按钮触发，弹出确认框，确认后标记删除
const DeleteForm = (row) => {
  deleteDialogVisible.value = true;
  Object.assign(NewForm, row);
};

// 重置新增/修改表单内容
const resetNewForm = () => {
  NewForm.lid = "";
  NewForm.strength = "";
  NewForm.did = "";
  NewForm.startdate = "";
  NewForm.enddate = "";
  NewForm.starttime = "";
  NewForm.endtime = "";
  NewForm.lightstate = "";
  NewForm.delstate = "0";
  NewForm.remark = "";
  NewForm.plantname = "";
};
// 页面加载时触发，请求数据，渲染表格
//定义定时器
let intervalId = null;
onMounted(() => {
  gettableData();
  getLightEquipment();
  // 每隔5分钟重新请求刷新数据
  intervalId = setInterval(() => {
    gettableData();
    getLightEquipment();
  }, 300000);
});
//页面销毁时清除定时器;
onUnmounted(() => {
  clearInterval(intervalId);
});
</script>

<style lang="scss" scoped>
.box {
  .top {
    display: flex;
    justify-content: space-between;
    .operation {
      display: flex;
      align-items: center;
    }
  }
  .main {
    .table {
      width: 100%;

      .hasRemark {
        text-decoration: underline;
      }
    }
  }
  .el-dialog {
    h1 {
      margin-bottom: 20px;
    }

    .form {
      .strengthInput {
        display: flex;
      }
    }
    .noRemark {
      color: #999;
    }
    .error-message {
      color: red;
    }
    .el-pagination {
      margin: 0;
      padding: 0;
      position: absolute;
      bottom: 21px;
    }

    .dialog-title {
      font-size: 18px;
      margin: 0 0 30px 0;
    }
  }
}
</style>
